package mskruch.gps.util;

import gpstools.data.UnsupportedFormatException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import mskruch.gps.Lap;
import mskruch.gps.Point;
import mskruch.gps.Track;
import mskruch.gps.calculation.Calculations;
import mskruch.gps.calculation.PointsCalculator;
import mskruch.gps.data.GpxExporter;
import mskruch.gps.data.TrackLoader;

public class CommandLineUtil {

    public static void main(String[] args) throws UnsupportedFormatException, IOException {
        if (args.length < 1) {
            printUsuage();
            return;
        }
        String filename = args[0];

        TrackLoader loader = new TrackLoader(filename);
        Track track = loader.nextTrack();

        if (args.length == 1) {
            System.out.println("File: " + filename);
            System.out.println("Track name: " + (track.getName() != null ? track.getName() : ""));
            System.out.println("Laps: " + track.getLaps().length);

            Lap[] laps = track.getLaps();
            int i = 1;
            for (Lap lap : laps) {
                PointsCalculator pc = Calculations.newPointsCalculator();
                pc.add(lap.getPoints());
                System.out.println(String.format("%3d: %10.2f %10.2f %10.2f", i++, pc.getDistance(),
                        pc.getElevationGain(), pc.getElevationLoss()));
            }
        } else {
            String command = args[1];
            if ("extract".equals(command)) {
                if (args.length < 3) {
                    printUsuage();
                    return;
                }
                String lapsParam = args[2];
                int i = Integer.valueOf(lapsParam) - 1;
                Point[] points = track.getLaps()[i].getPoints();
                new GpxExporter(points, "extracted lap").store("extracted.gpx");

                System.out.println("File extracted.gpx created");
            }
        }
    }

    private static void printUsuage() {
        try {
            InputStream resource = CommandLineUtil.class.getResourceAsStream("/command-line-usage.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource));
            String line;
            while ((line = reader.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Internal error");
            e.printStackTrace();
        }
    }

}
